<?php

namespace App\Http\Requests;

use App\Exceptions\AdminManageException;
use App\Services\AdminErrCode;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class ApiRequest extends FormRequest
{
    protected $AUTH_ERROR_ID = AdminErrCode::AUTHORIZE_ERROR_ID_UNKNOWN;

    /**
     * @param Validator $validator
     * @throws AdminManageException
     */
    protected function failedValidation(Validator $validator)
    {
        throw new AdminManageException(
            AdminErrCode::REQUEST_PARAMS_ERROR,
            $this->errorToString($this->formatErrors($validator))
        );
    }

    /**
     * @throws AdminManageException
     */
    protected function failedAuthorization()
    {
        throw new AdminManageException( AdminErrCode::AUTHORIZER_NOT_FOUND ,
            "登录用户权限认证失败[{$this->AUTH_ERROR_ID}]"
        );
    }


    /**
     * 数组错误信息转成分隔开的字符串
     *
     * @test
     * @see WechatRequestTest::test_wx_req_format_errors_to_string()
     *
     * @param array $rules_errors
     * @param string $glue
     * @return string
     */
    public function errorToString(array $rules_errors, $glue = ' , ')
    {
        return array_reduce(
            $rules_errors,
            /**
             * @param string $before - 前面拼接好的字符串
             * @param array $current - 当前错误数组
             * @return string
             */
            function ($before, array $current) use ($glue) {
                $prefix = $before ? $glue : '';
                return $before . $prefix . implode($glue, $current);
            },
            ''
        );
    }
}
